<template>
    <!-- <div class="miniAppLogin" > -->
        <div class="editor">
            <div class="editor-caption">
                <!-- <div class="arrow"></div> -->
                <div class="editor-title-wrapper">登录</div>
                <!-- <div class="nav-rightbtn-group">
                    <img :src="rightBtn" alt="">
                </div> -->
            </div>
            <div class="appContent" :style="{backgroundImage: 'url(' + loginConf.bgUrl + ')', backgroundSize:'100% 100%'}">
                <div class="contentForm">
                    <div class="iconStyle" v-if="loginConf.iconImg">
                        <van-image
                            width="80"
                            height="80"
                            :src="loginConf.iconImg"
                            />
                    </div>
                    <div class="formInfo" :style="{bottom: loginConf.formBottom+ 'px'}">
                        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
                            <el-form-item prop="tenantname" :style="{marginBottom: loginConf.spacing+'px'}">
                                <el-select type="text"  placeholder="请选择租户"
                                    :style="{ '--height-input': `${loginConf.inputHeight + 'px'}`,'--border-width': `${loginConf.isborder === 'yes' ? loginConf.borderWidth + 'px' : '0'}`,'--border-color': `${loginConf.borderColor}`,'--box-shadow': `${loginConf.boxShadow}`,'--border-radius': `${loginConf.borderRadius + 'px'}`,width:'100%'}"
                                    @change="handleCommand" v-model="active"
                                >
                                    <i slot="prefix" class="el-icon-s-custom"></i>
                                    <el-option v-for="(item) in tenantList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="username" :style="{marginBottom: loginConf.spacing+'px'}">
                                <el-input type="text"  :placeholder="loginConf.usePlaceholder"
                                    v-model="loginForm.username"
                                    :style="{ '--height-input': `${loginConf.inputHeight + 'px'}`,'--border-width': `${loginConf.isborder === 'yes' ? loginConf.borderWidth + 'px' : '0'}`,'--border-color': `${loginConf.borderColor}`,'--box-shadow': `${loginConf.boxShadow}`,'--border-radius': `${loginConf.borderRadius + 'px'}`}"
                                    >
                                    <i slot="prefix" :class="loginConf.useIcon"></i>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="password" :style="{marginBottom: loginConf.spacing+'px'}">
                                <el-input :type="passwordType"
                                    v-model="loginForm.password"
                                    :placeholder="loginConf.password"
                                    :style="{ '--height-input': `${loginConf.inputHeight + 'px'}`,'--border-width': `${loginConf.isborder === 'yes' ? loginConf.borderWidth + 'px' : '0'}`,'--border-color': `${loginConf.borderColor}`,'--box-shadow': `${loginConf.boxShadow}`,'--border-radius': `${loginConf.borderRadius + 'px'}`}">
                                    <i slot="prefix" :class="loginConf.passIcon"></i>
                                    <i slot="suffix" class="el-icon-view"   @click="showPassword"/>
                                </el-input>
                            </el-form-item>
                            <el-form-item prop="code">
                                <Verify
                                    @success="verifySuccess"
                                    :mode="'pop'"
                                    :captchaType="'blockPuzzle'"
                                    :imgSize="{ width: '330px', height: '155px' }"
                                    ref="verify"
                                />
                            </el-form-item>
                            <el-form-item style="width:100%;">
                                <el-button  type='button' size="medium"
                                    @click.native.prevent="handleLogin" :style="{height: '32px',width: '100%',fontSize: loginConf.fontSizeName+'px',letterSpacing: loginConf.nameSpacing+'px',color: loginConf.nameColor,backgroundColor: loginConf.bgColor}" class="btnUpdata">
                                        {{loginConf.btnName}}
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="el-login-footer">
                        <span :style="{fontSize: loginConf.footerFontSize+'px',color: loginConf.footerColor}">{{loginConf.loginFooter}}</span>
                    </div>
                </div>
            </div>
        </div>
    <!-- </div> -->
</template>

<script>

import rightBtn from '@/assets/images/rightBtn.png'
import Vue from 'vue';
import { Image as VanImage } from 'vant';
import {getAccessToken, encryption} from '@/utils/auth'
import Verify from "@/components/verifition/Verify";
import { getTenantIdByName,  listLinshi} from "@/api/system/tenant";
import {getAppIdData} from "@/api/custom/portalDesigner"
import Cookies from "js-cookie";
import { getVerifyCaptcha } from "@/api/system/systemConfig";
import { getStore, setStore } from '@/utils/store'
Vue.use(VanImage);

export default {
    components: {
        Verify
    },
    props: ['loginFormList'],
    data() {
        return {
            active:'',
            token: '', //接口请求token
            loginConf: {
                bgUrl: '',
                iconImg: '',
                usePlaceholder: '请输入用户名',
                useIcon: 'el-icon-user',
                password: '请输入密码',
                passIcon: 'el-icon-key',
                formBottom: '100',
                inputHeight: '34',
                spacing: '14',
                btnName: '登录',
                fontSizeName: '14',
                nameSpacing: '14',
                nameColor: '#ffffff',
                bgColor: '#409eff',
                footerFontSize: '10',
                footerColor: '#999',
                loginFooter: 'Copyright © 2020-2021 中移系统集成有限公司',
                borderWidth: '1',
                borderColor: '#DCDFE6',
                boxShadow: 'null',
                isborder: 'yes',
                borderRadius: '4'
            },
            rightBtn: rightBtn,
            tenantList: [],
            loginForm: {
                username: this.$store.state.mobile.isJump ? 'admin' : "",
                password: this.$store.state.mobile.isJump ? '' : "",
                code: "",
                uuid: "",
                tenantId: "",
            },
            passwordType: "password",
            loginRules: {
                username: [
                { required: true, trigger: "blur", message: "用户名不能为空" }
                ],
                password: [
                { required: true, trigger: "blur", message: "密码不能为空" }
                ],
            },
            loginLoading:null
        }
    },
    mounted() {
      this.token = getAccessToken()

    },
    created() {
        this.getTenantId();
        this.getCookie();

    this.getLoginData()
        if(this.$store.state.mobile.isJump){
            this.loginConf = this.loginFormList
        }else{
            // this.getLoginConf()
        }
    },
    methods: {
        getLoginData() {
      this.$store.dispatch('GetLoginConf').then(() => {
           this.loginConfig = this.$store.state.user && this.$store.state.user.loginConfigData
           document.title = this.$store.state.user && this.$store.state.user.loginConfigData.loginName
            var link = document.querySelector("link[rel*='icon']") || document.createElement('link')
            link.type = 'image/x-icon'
            link.rel = 'shortcut icon'
            link.href = this.$store.state.user.loginConfigData.browserUrl
            document.getElementsByTagName('head')[0].appendChild(link)
        })
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const tenantName = Cookies.get('tenantName');
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName,
      };
    },
        getLoginConf () {
            let id = localStorage.getItem('mobileAppid');
            getAppIdData({
                id:id,
                // id:'wxf75cabc5c8b712a4',
                isReference:1
                }).then(res=>{
                    this.loginLoading.close();
                if(res.code===0){
                    if(!res.data){
                        this.$message.warning('请先发布小程序');
                        return;
                    }
                    this.loginConf = JSON.parse(res.data.portal_json_message)?.loginForm
                    let obj = JSON.parse(res.data.portal_json_message);
                     let arr = [];
                     obj.pageList.forEach((item) => {
                        if (Array.isArray(item.children)) {
                            arr.push(...item.children);
                        }
                        });
                    let drawobj = {
                        pageListAll:obj,
                        curPath:arr[0].name
                    }
                    window.localStorage.setItem('mobileDrawObj',JSON.stringify(drawobj));
                    let curPath = drawobj.curPath;
                    let mobileTurn = window.localStorage.getItem('mobileTurn');
                    if(mobileTurn){
                        window.localStorage.removeItem('mobileTurn')
                        window.location.href = mobileTurn;
                    }else{
                        this.$router.push(`/iphonePath/${curPath}`)
                    }
                    }
                }).catch(e=>{
                    this.loginLoading.close();
                })
        },
        showPassword() {
            this.passwordType == ""
                ? (this.passwordType = "password")
                : (this.passwordType = "");
        },
        handleLogin() {
    getVerifyCaptcha().then((res) => {
if(res.code === 0){
    if(res.data){
       this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$refs.verify.show();
        }
      });
    }else{
        this.verifySuccess('')
    }
}
})
    // this.$refs.loginForm.validate(valid => {
    //     if (valid) {
    //         this.$refs.verify.show();
    //     }
    // });
},
 verifySuccess(params) {
    this.loginForm.code = params.captchaVerification;
    this.loginForm.tenantId = this.active
    let password = encryption(this.loginForm.password)  //密码加密
    setStore({ name: 'tenantId', content: this.loginForm.tenantId  })
    const data = {
        code: this.loginForm.code,
        password: password,
        tenantId: this.loginForm.tenantId,
        tenantName: '',
        username: this.loginForm.username
    }
    // 发起登陆
    if(this.$store.state.mobile.isJump) { //预览
        this.$emit('isJumpLogin')
    }else{
        if(this.$store.state.mobile.userAgent === "mobile"){
            this.loginLoading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
          text:'登录中'
        });
           }
        this.$store.dispatch("LoginMini", data).then(() => {
            this.$websocket.initWebSocket(getAccessToken())
            console.log('abbbbbb');
            this.getLoginConf()

            }).catch(() => {
        });
    }

},
         getTenantId() {
            if(this.$store.state.mobile.isJump){ //预览
                listLinshi().then((res) => {
                    this.tenantList = res.data
                })
            }else{
                getTenantIdByName().then((res) => {
                    this.tenantList = res.data
                })
            }
        },
         handleCommand (command) {
            // 切换租户清空 账号 密码
            this.loginForm.username = ''
            this.loginForm.password = ''
        },
    }
}
</script>
<style lang='scss' scoped>
@import '@/styles/loginFrom';
.miniAppLogin{
    width: 375px;
    height: 667px;
    position: absolute;
    left: 50%;
    background: #fff;
    transform: translate(-50%, 0);

}
.editor{
        width: 100%;
        height: 100%;
    }
.editor-title-wrapper{
    width: 100%;
    text-align: center;
}
@media only screen and (min-width: 768px) {
   .editor-caption{
    width:375px;
    margin:auto;
   }
  }
</style>
